import {fetchList, add, edit, del} from '@/services/mall/MallPkgItem';
import {message} from 'antd';

export default {
  namespace: 'PMallPkgItems',

  state: {
    list: []
  },

  effects: {
    * fetchList({payload}, {call, put}) {
      const response = yield call(fetchList, payload);
      if (response.code === 0) {
        yield put({
          type: 'chgList',
          payload: response.data.map(d => {
            if (d.itemType === 0) {
              d.name = d.mallGoods ? d.mallGoods.name : '-';
              d.tag = d.mallGoodsSpec ? d.mallGoodsSpec.name : '-';
              d.sellPrice = d.mallGoodsSpec ? (d.mallGoodsSpec.sellPrice / 100).toFixed(2) : '-';
              d.stock = d.mallGoodsSpec ? d.mallGoodsSpec.stock : '-';
            }
            if (d.itemType === 1) {
              d.name = d.mallServe ? d.mallServe.name : '-';
              d.tag = d.mallServeCard ? d.mallServeCard.name : '-';
              if (d.serveCardId > 0) {
                d.sellPrice = d.mallServeCard ? (d.mallServeCard.sellPrice / 100).toFixed(2) : '-';
                d.stock = d.mallServeCard ? d.mallServeCard.stock : '-';
              } else {
                d.sellPrice = d.mallServe ? (d.mallServe.sellPrice / 100).toFixed(2) : '-';
                d.stock = d.mallServe ? d.mallServe.stock : '-';
              }
            }
            return d;
          }),
        });
      }
    },

    * add({payload, callback}, {call}) {
      const response = yield call(add, payload);
      if (response.code === 0) {
        message.success('添加成功').then();
        callback && callback();
      }
    },

    * edit({payload, callback}, {call}) {
      const response = yield call(edit, payload);
      if (response.code === 0) {
        message.success('修改成功').then();
        callback && callback();
      }
    },

    * del({payload, callback}, {call}) {
      const response = yield call(del, payload);
      if (response.code === 0) {
        message.success('删除成功').then();
        callback && callback();
      }
    },

  },

  reducers: {
    chgList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
  },
};
